# -*- coding: utf-8 -*-
"""
从第1行到第63行这部分python代码，对应的是matlab的第1行到第63行
对应Matlab文件: Case_Test.m (作为入口脚本)
"""

import numpy as np
import matplotlib.pyplot as plt

from func_vpe import func_vpe
from func_extract_field import func_extract_field


def func_cs_mapping(shape, dx, h_max, w_max):
    """
    从第65行到第93行这部分python代码，对应的是matlab的第65行到第93行
    Matlab内嵌函数: func_cs_mapping
    """
    if shape == 1:
        height = h_max
        width = w_max
        cs = [width, height]
    elif shape == 4:
        x_b1 = 2
        y_b2 = 1.5
        w_half = w_max / 2
        r2_bottom = w_half
        h_bottom = y_b2 - 2 * dx
        h_top = h_max - h_bottom
        cs = [w_half, h_top, r2_bottom, h_bottom, x_b1, y_b2]
    else:
        w_half = w_max / 2
        h_top = w_half
        h_bottom = h_max - h_top
        r2_bottom = w_half
        cs = [w_half, h_top, r2_bottom, h_bottom]
    return cs


def main():
    # 从第1行到第22行，对应matlab的第1行到第22行 (参数定义)
    shape = 1
    sigma = 0.001
    eps_r = 5
    tx1 = 0.5
    tx2 = 1.0
    f = 2.4e9
    dx = 0.05
    ds = 0.25
    distance = 500
    h_max = 4
    w_max = 5
    cs = func_cs_mapping(shape, dx, h_max, w_max)

    k_w0 = 0.9
    bc = 1
    tx = [None] * 4
    tx[0] = tx1
    tx[1] = tx2
    tx[2] = 1
    tx[3] = 20

    # Rx用于绘图
    rx = [None] * 4
    rx[0] = tx1
    rx[1] = tx2
    rx[2] = 1
    rx[3] = ds

    # 从第25行到第27行，对应matlab的第25行到第27行 (仿真)
    _, rss = func_vpe(f, eps_r, sigma, distance, tx, k_w0, shape, bc, cs, dx, ds)

    # 从第29行到第47行，对应matlab的第29行到第47行 (绘图)
    p_dist = np.arange(0, distance + 1e-9, ds)
    pl = func_extract_field(f, distance, tx, rx, shape, cs, dx, ds, rss)

    plt.figure()
    plt.plot(p_dist[: len(pl)], pl, "-k", linewidth=1.5)
    plt.grid(True)
    plt.xlim([0, distance])
    plt.ylim([-80, 0])
    plt.xlabel("Axial Distance [m]")
    plt.ylabel("Received Power [dBm]")
    plt.gca().set_aspect(1.5 / 1)
    plt.show()


if __name__ == "__main__":
    main()
